package com.xkw.autocode.web.system.controller;

import java.io.File;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.xkw.autocode.base.BaseController;
import com.xkw.autocode.util.FileUtils;
import com.xkw.autocode.util.FolderTreeUtil;
import com.xkw.autocode.web.common.Result;
import com.xkw.autocode.web.system.SystemUrlUtil;

/**
 * 文件系统相关的Controller处理类
 * 
 * @author xiangkaiwei
 *
 */
@Controller
public class FileSystemController extends BaseController {

	@GetMapping(value = SystemUrlUtil.FILE_VIEW)
	public ModelAndView toExportFromSql(String filePath) {
		ModelAndView modelAndView = new ModelAndView();

		// 查询所有模板
		modelAndView.addObject("filePath", filePath);

		modelAndView.setViewName("fileView");
		return modelAndView;
	}
	
	/**
	 * 获取文件夹的树形结构
	 * 
	 * @param request
	 * @param response
	 * @param dirPath
	 *            文件夹路径
	 * @return
	 */
	@RequestMapping(value = SystemUrlUtil.FILE_TREE)
	@ResponseBody
	public Result fileTree(String filePath) {
		return Result.ok().put("treeList", FolderTreeUtil.getTrees(filePath));
	}

	/**
	 * 读取文件内容
	 * 
	 * @param request
	 * @param response
	 * @param filePath
	 *            文件路径
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = SystemUrlUtil.FILE_READ)
	@ResponseBody
	public Object view(HttpServletRequest request, HttpServletResponse response, String filePath) throws Exception {

		List<String> lines = FileUtils.readFile(new File(filePath));

		StringBuilder sbl = new StringBuilder();

		for (String line : lines) {
			sbl.append(line).append("\n");
		}

		Map<String, String> map = new HashMap<>();

		map.put("lines", sbl.toString());

		return map;
	}
}
